<template>
    <div class="medical-safety-container">
        <global-search @submitSearch="submitSearch" class="global-tool-search"/>
        <div class="page-height-box">
            <view-card :cardData="cardData"/>
            <div class="echart-table-box">
            <el-row :gutter="10">
                <el-col :span="12">
                    <div class="content">
                        <p class="title">安全分析</p>
                        <data-chart :chartData="safetyEchart"/>
                    </div>
                </el-col>
                <el-col :span="12">
                    <div class="content">
                        <p class="title">死亡病组TOP10</p>
                        <ul v-if="top10List.length > 0" class="my-scrollbar">
                            <li v-for="item in top10List">
                                <el-progress :stroke-width="15" :percentage="total ? item.value / total * 100 : 0"
                                             :color="item.color"
                                             :format="progressFormat"></el-progress>
                                <p class="li-item-text">{{item.key}}</p>
                            </li>
                        </ul>
                        <p v-else class="no-data">暂无数据</p>
                    </div>
                </el-col>
                <el-col :span="24">
                    <div class="content">
                        <div class="title-tool-btn">
                            <p class="title">汇总列表</p>
                            <el-button type="text" class="export-btn" v-auth="{code: 200004003001}" @click="toExport">
                                <svg-icon icon-class="export"/>
                                导出
                            </el-button>
                        </div>
                        <el-table
                            border
                            :data="tableData"
                            tooltip-effect="light"
                            style="width: 100%"
                            :empty-text="emptyText"
                            @selection-change="handleSelectionChange">
                            <el-table-column
                                show-overflow-tooltip
                                type="selection"
                                align="center"
                                width="50">
                            </el-table-column>
                            <el-table-column
                                show-overflow-tooltip
                                prop="date"
                                type="index"
                                align="center"
                                label="序号"
                                width="50">
                            </el-table-column>
                            <el-table-column
                                show-overflow-tooltip
                                prop="department"
                                align="center"
                                label="科室名称"
                                min-width="120">
                            </el-table-column>
                            <el-table-column
                                show-overflow-tooltip
                                v-if="isShowDoctor"
                                prop="resident"
                                align="center"
                                label="住院医生"
                                min-width="110">
                            </el-table-column>
                            <el-table-column
                                show-overflow-tooltip
                                prop="drgCase"
                                align="center"
                                sortable
                                label="入组病案数"
                                min-width="160">
                            </el-table-column>
                            <el-table-column
                                show-overflow-tooltip
                                prop="deathRate"
                                align="center"
                                sortable
                                label="死亡率"
                                min-width="160">
                                <template slot-scope="scope">
                                    {{scope.row.deathRate | toPercentage}}
                                </template>
                            </el-table-column>
                            <el-table-column
                                show-overflow-tooltip
                                prop="low"
                                align="center"
                                sortable
                                label="低风险死亡"
                                min-width="160">
                            </el-table-column>
                            <el-table-column
                                show-overflow-tooltip
                                prop="lowMiddle"
                                align="center"
                                sortable
                                label="中低风险死亡"
                                min-width="160">
                            </el-table-column>
                            <el-table-column
                                show-overflow-tooltip
                                prop="middleHigh"
                                align="center"
                                sortable
                                label="中高风险死亡"
                                min-width="160">
                            </el-table-column>
                            <el-table-column
                                show-overflow-tooltip
                                prop="high"
                                align="center"
                                sortable
                                label="高风险死亡"
                                min-width="160">
                            </el-table-column>
                            <el-table-column
                                show-overflow-tooltip
                                label="操作"
                                align="center"
                                min-width="100"
                                fixed="right">
                                <template slot-scope="scope">
                                    <el-button type="text" @click="toPageInfo(scope.row)">明细</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </el-col>
            </el-row>
        </div>
        </div>
    </div>
</template>

<script>
    import {
        safetyRiskLevel,
        safetyDRGDeathTop,
        safetySummaryTable,
        exportSafetySummary
    } from '@/api/data-analysis/medical-safety'
    import {toPercentage} from '@/utils/filters'
    import DataChart from '@/components/DataChart'
    import ViewCard from '@/components/ViewCard'
    import FileSaver from 'file-saver'
    import ExcelJS from 'exceljs'

    export default {
        name: 'Dashboard',
        data () {
            return {
                // 是否显示住院医生
                isShowDoctor: false,
                // 安全分析
                safetyEchart: {
                    xAxis: [],
                    series: [{
                        name: '低风险组死亡',
                        data: []
                    }, {
                        name: '中低风险组死亡',
                        data: []
                    }, {
                        name: '中高风险组死亡',
                        data: []
                    }, {
                        name: '高风险组死亡',
                        data: []
                    }],
                    rate: [],
                    yAxisName: ['(人)'],
                    id: 'safetyEchart'
                },
                // 卡片数据
                cardData: [
                    {
                        title: 'DRG入组病案数',
                        data: 0,
                        scale: '0%',
                        tips: '已入组的病案数',
                        pageName: 'SafetyListIndex',
                        query: {
                            deathClass: 0
                        }
                    }, {
                        title: '死亡例数',
                        data: 0,
                        scale: '0%',
                        tips: '死亡的病案数',
                        pageName: 'SafetyListIndex',
                        query: {
                            deathClass: 1
                        }
                    }, {
                        title: '低风险组死亡病案',
                        data: 0,
                        scale: '0%',
                        tips: '低风险组死亡病案数',
                        pageName: 'SafetyListIndex',
                        query: {
                            deathClass: 2
                        }
                    }, {
                        title: '中低风险组死亡病案',
                        data: 0,
                        scale: '0%',
                        tips: '中低风险死亡病案数',
                        pageName: 'SafetyListIndex',
                        query: {
                            deathClass: 3
                        }
                    }, {
                        title: '中高风险组死亡病案',
                        data: 0,
                        scale: '0%',
                        tips: '中高风险组死亡病案数',
                        pageName: 'SafetyListIndex',
                        query: {
                            deathClass: 4
                        }
                    }, {
                        title: '高风险组死亡病案',
                        data: 0,
                        scale: '0%',
                        tips: '高风险组死亡病案数',
                        pageName: 'SafetyListIndex',
                        query: {
                            deathClass: 5
                        }
                    }],
                // top10总数
                total: 0,
                // top10数据
                top10List: [],
                // 表格数据
                tableData: [],
                // 选中的数据
                multipleSelection: [],
                // 空数据时显示的文本内容
                emptyText: '暂无数据',
                // 使用储存的数据，不去请求
                useStoreRiskLevel: false,
                useStoreDRGDeathTop: false,
                useStoreSummary: false,
                // 导出的全部数据
                allexportData: []
            }
        },
        created () {
            // tags判断入口是否从选项卡进入
            this.useStoreRiskLevel = this.$route.query.tags === 'tags'
            this.useStoreDRGDeathTop = this.$route.query.tags === 'tags'
            this.useStoreSummary = this.$route.query.tags === 'tags'
        },
        mounted () {
        },
        methods: {
            /**
             * 提交查询
             * @param form 筛选条件
             */
            submitSearch (form) {
                this.isShowDoctor = form.department !== ''
                this.getSafetyRiskLevel(form)
                this.getSafetyDRGDeathTop(form)
                this.getSafetySummaryTable(form)
            },
            /**
             * 风险组死亡情况查询
             * @param params 查询参数
             */
            getSafetyRiskLevel (params) {
                if (this.getSession(this.$route.name, 'safetyRiskLevel') && this.useStoreRiskLevel) {
                    this.useStoreRiskLevel = false
                    let res = this.getSession(this.$route.name, 'safetyRiskLevel')
                    this.emptyText = '暂无数据'
                    if (res.code.toString() === '200') {
                        this.cardData[0].data = res.data.totalCase
                        this.cardData[0].scale = res.data.groupRate
                        this.cardData[1].data = res.data.deadCase
                        this.cardData[1].scale = res.data.deathRate
                        this.cardData[2].data = res.data.lowDeath
                        this.cardData[2].scale = res.data.lowDeathRate
                        this.cardData[3].data = res.data.lowMiddleDeath
                        this.cardData[3].scale = res.data.lowMiddleDeathRate
                        this.cardData[4].data = res.data.middleHighDeath
                        this.cardData[4].scale = res.data.middleHighDeathRate
                        this.cardData[5].data = res.data.highDeath
                        this.cardData[5].scale = res.data.highDeathRate
                        this.safetyEchart = {
                            xAxis: res.data.month,
                            series: [{
                                name: '低风险组死亡',
                                data: res.data.lowNum
                            }, {
                                name: '中低风险组死亡',
                                data: res.data.lowMiddleNum
                            }, {
                                name: '中高风险组死亡',
                                data: res.data.middleHighNum
                            }, {
                                name: '高风险组死亡',
                                data: res.data.highNum
                            }],
                            rate: [{
                                name: '低风险组死亡',
                                data: res.data.lowRate
                            }, {
                                name: '中低风险组死亡',
                                data: res.data.lowMiddleRate
                            }, {
                                name: '中高风险组死亡',
                                data: res.data.middleHighRate
                            }, {
                                name: '高风险组死亡',
                                data: res.data.highRate
                            }],
                            yAxisName: ['(人)'],
                            id: 'safetyEchart'
                        }
                    }
                } else {
                    safetyRiskLevel(params).then(res => {
                        this.useStoreRiskLevel = false
                        this.setSession(this.$route.name, {safetyRiskLevel: res})
                        if (res.code.toString() === '200') {
                            this.cardData[0].data = res.data.totalCase
                            this.cardData[0].scale = res.data.groupRate
                            this.cardData[1].data = res.data.deadCase
                            this.cardData[1].scale = res.data.deathRate
                            this.cardData[2].data = res.data.lowDeath
                            this.cardData[2].scale = res.data.lowDeathRate
                            this.cardData[3].data = res.data.lowMiddleDeath
                            this.cardData[3].scale = res.data.lowMiddleDeathRate
                            this.cardData[4].data = res.data.middleHighDeath
                            this.cardData[4].scale = res.data.middleHighDeathRate
                            this.cardData[5].data = res.data.highDeath
                            this.cardData[5].scale = res.data.highDeathRate
                            this.safetyEchart = {
                                xAxis: res.data.month,
                                series: [{
                                    name: '低风险组死亡',
                                    data: res.data.lowNum
                                }, {
                                    name: '中低风险组死亡',
                                    data: res.data.lowMiddleNum
                                }, {
                                    name: '中高风险组死亡',
                                    data: res.data.middleHighNum
                                }, {
                                    name: '高风险组死亡',
                                    data: res.data.highNum
                                }],
                                rate: [{
                                    name: '低风险组死亡',
                                    data: res.data.lowRate
                                }, {
                                    name: '中低风险组死亡',
                                    data: res.data.lowMiddleRate
                                }, {
                                    name: '中高风险组死亡',
                                    data: res.data.middleHighRate
                                }, {
                                    name: '高风险组死亡',
                                    data: res.data.highRate
                                }],
                                yAxisName: ['(人)'],
                                id: 'safetyEchart'
                            }
                        }
                    })
                }
            },
            /**
             * 死亡病组top10查询
             * @param params 查询参数
             */
            getSafetyDRGDeathTop (params) {
                this.total = 0
                this.top10List = []
                if (this.getSession(this.$route.name, 'safetyDRGDeathTop') && this.useStoreDRGDeathTop) {
                    this.useStoreDRGDeathTop = false
                    let res = this.getSession(this.$route.name, 'safetyDRGDeathTop')
                    this.emptyText = '暂无数据'
                    if (res.code.toString() === '200') {
                        res.data.forEach((item, index) => {
                            this.top10List.push({
                                key: item.key,
                                value: parseInt(item.value)
                            })
                            this.top10List[index].color = '#e2e3e6'
                            switch (index) {
                            case 0:
                                this.top10List[index].color = '#F34726'
                                break
                            case 1:
                                this.top10List[index].color = '#F09510'
                                break
                            case 2:
                                this.top10List[index].color = '#B4B8BC'
                                break
                            }
                            this.total += parseInt(item.value)
                        })
                    }
                } else {
                    safetyDRGDeathTop(params).then(res => {
                        this.useStoreDRGDeathTop = false
                        this.setSession(this.$route.name, {safetyDRGDeathTop: res})
                        if (res.code.toString() === '200') {
                            res.data.forEach((item, index) => {
                                this.top10List.push({
                                    key: item.key,
                                    value: parseInt(item.value)
                                })
                                this.top10List[index].color = '#e2e3e6'
                                switch (index) {
                                case 0:
                                    this.top10List[index].color = '#F34726'
                                    break
                                case 1:
                                    this.top10List[index].color = '#F09510'
                                    break
                                case 2:
                                    this.top10List[index].color = '#B4B8BC'
                                    break
                                }
                                this.total += parseInt(item.value)
                            })
                        }
                    })
                }
            },
            /**
             * 汇总列表查询
             * @param params 查询参数
             */
            getSafetySummaryTable (params) {
                this.emptyText = '加载中...'
                if (this.getSession(this.$route.name, 'safetySummaryTable') && this.useStoreSummary) {
                    this.useStoreSummary = false
                    let res = this.getSession(this.$route.name, 'safetySummaryTable')
                    this.emptyText = '暂无数据'
                    if (res.code.toString() === '200') {
                        this.tableData = res.data
                        this.tableData.forEach((item, index) => {
                            this.tableData[index] = {
                                ...item,
                                index
                            }
                        })
                    }
                } else {
                    safetySummaryTable(params).then(res => {
                        this.useStoreSummary = false
                        this.setSession(this.$route.name, {safetySummaryTable: res})
                        this.emptyText = '暂无数据'
                        if (res.code.toString() === '200') {
                            this.tableData = res.data
                            this.tableData.forEach((item, index) => {
                                this.tableData[index] = {
                                    ...item,
                                    index
                                }
                            })
                        }
                    }).catch(() => {
                        this.emptyText = '暂无数据'
                    })
                }
            },
            /**
             * 设置右侧显示文字
             * @param percentage 当前进度
             */
            progressFormat (percentage) {
                return Math.round(percentage * this.total / 100) + '例'
            },
            /**
             * 表格数据选中
             */
            handleSelectionChange (val) {
                this.multipleSelection = val
            },
            /**
             * 获取选中id
             */
            getSelectId () {
                let arr = []
                if (this.multipleSelection.length) {
                    this.multipleSelection.forEach(item => {
                        arr.push(item.index)
                    })
                    return arr
                } else {
                    return false
                }
            },
            /**
             * 导出汇总列表
             */
            toExport () {
                let params = JSON.parse(JSON.stringify(this.$store.state.search.searchForm[this.$route.name]))
                params.indexList = this.getSelectId() || []
                this.$store.dispatch('app/UpdateLoadingText', '0%')
                this.$store.dispatch('app/UpdateIsExport', true)
                this.$store.dispatch('app/UpdateLoading', true)
                params.pageIndex = 1
                params.pageSize = 1000
                this.allexportData = []
                this.sendRequest(params)
            },
            /**
             * 发送请求
             * @param params 请求参数
             */
            sendRequest (params) {
                let allIndex = Math.ceil(this.total / 1000)
                exportSafetySummary(params).then(res => {
                    if (res.code.toString() === '200') {
                        this.$store.dispatch('app/UpdateLoadingText', parseInt(params.pageIndex / allIndex * 95) + '%')
                        this.allexportData = this.allexportData.concat(res.data)
                        if (params.pageIndex < allIndex) {
                            this.sendRequest({...params, pageIndex: params.pageIndex + 1})
                        } else {
                            this.exportDataList('医疗安全汇总列表', this.allexportData)
                        }
                    } else {
                        this.$store.dispatch('app/UpdateIsExport', false)
                        this.$store.dispatch('app/UpdateLoading', false)
                        this.$message.error('导出失败')
                    }
                }).catch(() => {
                    this.$store.dispatch('app/UpdateIsExport', false)
                    this.$store.dispatch('app/UpdateLoading', false)
                    this.$message.error('导出失败')
                })
            },
            /**
             * 导出excel表头
             */
            getHeader () {
                let arr = [{
                    header: '序号', key: 'index', width: 10
                }, {
                    header: '科室名称', key: 'department', width: 24
                }, {
                    header: '住院医生', key: 'resident', width: 24
                }, {
                    header: '入组病案数', key: 'drgCase', width: 24
                }, {
                    header: '死亡率', key: 'deathRate', width: 24
                }, {
                    header: '低风险死亡', key: 'low', width: 24
                }, {
                    header: '中低风险死亡', key: 'lowMiddle', width: 24
                }, {
                    header: '中高风险死亡', key: 'middleHigh', width: 24
                }, {
                    header: '高风险死亡', key: 'high', width: 24
                }]
                if (!this.isShowDoctor) {
                    arr.splice(2, 1)
                }
                return arr
            },
            /**
             * 导出列表excel
             */
            exportDataList (name, data) {
                let workbook = new ExcelJS.Workbook()
                workbook.creator = 'lyliang'
                workbook.views = [{
                    x: 0,
                    y: 0,
                    firstSheet: 0,
                    activeTab: 1,
                    visibility: 'visible'
                }]
                let worksheet = workbook.addWorksheet('Sheet1')
                worksheet.columns = this.getHeader()
                for (let i = 0; i < data.length; i++) {
                    data[i].index = i + 1
                    data[i].deathRate = toPercentage(data[i].deathRate)
                    worksheet.addRow(data[i])
                    worksheet.getRow(i + 1).alignment = {vertical: 'middle', horizontal: 'center'}
                    let rate = parseInt((i + 1) / data.length * 0.03 * 100 + 95) + '%'
                    this.$store.dispatch('app/UpdateLoadingText', rate)
                }
                worksheet.getRow(data.length + 1).alignment = {vertical: 'middle', horizontal: 'center'}
                workbook.xlsx.writeBuffer().then(data => {
                    this.$store.dispatch('app/UpdateLoadingText', '99%')
                    let blob = new Blob([data], {type: 'EXCEL_TYPE'})
                    FileSaver.saveAs(blob, `${this.parseTime(new Date().getTime())} ${name}.xlsx`)
                    this.$store.dispatch('app/UpdateLoadingText', '100%')
                    this.$store.dispatch('app/UpdateIsExport', false)
                    this.$store.dispatch('app/UpdateLoading', false)
                })
            },
            /**
             * 查看数据详情
             * @param row 行数据
             */
            toPageInfo (row) {
                let query = JSON.parse(JSON.stringify(this.$store.state.search.searchForm[this.$route.name]))
                this.setGetStore('SafetyListIndex', {...query, department: row.dep, depName: row.department, resident: this.isShowDoctor ? row.resident : ''})
                this.$router.push({name: 'SafetyListIndex', query: {department: row.dep, depName: row.department}})
            }
        },
        filters: {
            toPercentage
        },
        components: {
            ViewCard,
            DataChart
        }
    }
</script>

<style scoped lang="scss">
    .medical-safety-container {
        .echart-table-box {
            .el-col {
                &:nth-child(3) {
                    margin-bottom: 0;
                    height: auto;
                    .content {
                        min-height: calc(100vh - 652px);
                    }
                }
            }
        }
    }
</style>
